<?php
class MCar extends MY_Model {

	const STATE_USEFUL = 0; // 未出租
	const STATE_UNABLE = 1; // 已出租
	const STATE_BROKEN = 2; // 已损坏
	const STATE_FIXED = 3; // 维修中

	protected $table = 'car';

    function __construct() {
        parent::__construct();
    }

    public static function getState($state=NULL){
        $define = array(self::STATE_USEFUL=>'<label class="label label-success">未出租</label>',self::STATE_UNABLE=>'<label class="label label-primary">已出租</label>',self::STATE_BROKEN=>'<label class="label label-warning">已损坏</label>',self::STATE_FIXED=>'<label class="label label-danger">维修中</label>');
    	if($state === NULL){
    		return $define;
    	}else{
    		return key_exists($state, $define)?$define[$state]:'';
    	}
    }

	public function getList($limit){
		$this->db->select( '*');
		$this->db->distinct();
		$this->db->from($this->table);
		$this->db->limit($limit['limit'],$limit['offset']);
		$this->formfilter->doFilter();
        $this->db->order_by('id', 'desc');
        $query = $this->db->get();
		return $query->result();
	}

	public function getCount(){
		$this->db->select('count(distinct id) as num');
		$this->db->from($this->table);
		$this->formfilter->doFilter();
		$tmp = $this->db->get()->result();
		return (int)$tmp[0]->num;
	}

	public function getById($id){
		$query = $this->db->where('id',$id)->get($this->table);
		return $query->row();
	}

    //获取测评统计信息
    public function getAllData(){
        $this->db->select('
            sum(case when status = 0 then 1 else 0 end ) as free_num,
            sum(case when status = 1 then 1 else 0 end ) as used_num,
            sum(case when status = 2 then 1 else 0 end ) as broken_num,
            sum(case when status = 3 then 1 else 0 end ) as fixed_num,
            count(id) as total_num
            ',false);
        $this->db->from($this->table);
        return $this->db->get()->row();
    }

    public function getPieData($group){
        $keys = [0,1,2,3];
        $this->db->select("count(id) as car_num,status");
        $this->db->from($this->table);
        $this->db->group_by('status');
        $list = $this->db->get()->result();
        $return = array();
        foreach ($group as $k => $v){
            $return[$k]['name'] = $v;
            $return[$k]['value'] = 0;
        }

        foreach ($list as $v){
            $index = array_search($v->status,$keys);
            $name = $group[$index];
            $return[$index] = ['name' => $name,'value' => (int)$v->car_num];
        }
        return $return;
    }
}
